<template>
  <d2-container>
  <div class="app-container">
    <el-container :style="'height:'+containerHeight+'px'">
      <el-aside class="tree-area">
        <el-tree
          ref="buildTree"
          :style="'height:'+containerHeight+'px'"
          highlight-current
          node-key="buildingId"
          :data="dataList"
          :props="menuListTreeProps"
          @node-click="selectBuild"
          default-expand-all
          :expand-on-click-node="false"
        >
        </el-tree>
      </el-aside>
      <el-main class="theme-front-color">
        <el-row>
          <div class="search-area">
            <el-form label-position="right" :model="dataForm" :inline="true">
              <div style="font-size:15px;display:inline-block; float:left;">
                <el-form-item label="分类" label-width="40px">
                  <el-select v-model="dataForm.energyType"  style="width: 100px;" placeholder="请选择"  size="mini">
                    <el-option
                      v-for="(item, index) in meterTypeList" :key="index"
                      :label="item.paramValue"
                      :value="item.paramKey">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="日期" label-width="40px">
                  <el-date-picker
                    v-model="dataForm.date"
                    placeholder="时间范围"
                    style="width: 150px;"
                    class="filter-item"
                    size="mini"
                    :type="dataForm.dateType"
                    suffix-icon="el-icon-date"
                    clearable
                    @keyup.enter.native="getPowerDataList"
                  >
                  </el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-radio-group v-model="dataForm.dateType" size="mini">
                    <el-radio-button :label="item.date" v-for="(item, index) in Config.searchDate" :key="index">
                      {{item.label}}
                    </el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </div>
              <div style="display:inline-block; ">
                <!--<el-form-item>-->
                <!--<el-button-group>-->
                    <!--<el-button v-if="showchart" size="mini" icon="el-icon-menu" @click="changeShowType">表格</el-button>-->
                    <!--<el-button v-else size="mini" icon="el-icon-picture" @click="changeShowType">图表</el-button>-->
                  <!--</el-button-group>-->
                <!--</el-form-item>-->
                <el-form-item>
                  <el-button
                    class="filter-item"
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="getPowerDataList"
                  >查询</el-button>
                  <!--<el-button-->
                      <!--class="filter-item"-->
                      <!--type="primary"-->
                      <!--icon="el-icon-download"-->
                      <!--size="mini"-->
                      <!--@click="exoprtData"-->
                  <!--&gt;导出</el-button>-->
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-row>
        <div style="margin-top:20px;" v-show="showchart">
          <el-row :gutter="10">
            <el-col :span="16">
              <div id="businessAreaChart" class="busi-chart" :style="'height:'+chartHeight/2+'px;'"></div>
            </el-col>
            <el-col :span="8">
              <div id="chartTwo" class="busi-chart"  :style="'height:'+chartHeight/2+'px;'"></div>
            </el-col>
          </el-row>
        </div>
        <div v-show="showchart">
          <div id="businessChartCompare" class="busi-chart" :style="'height:'+chartHeight/2+'px;'"></div>
        </div>
        <div style="margin-top:20px;" v-show="!showchart">
         <el-table
            :data="departTableDataList"
            border
            :height="chartHeight"
            style="width: 100%; height: 400px;overflow:auto;"
          >
            <el-table-column prop="index" header-align="center" align="center" width="70" label="序号"></el-table-column>
            <el-table-column
              prop="buildName"
              header-align="center"
              align="center"
              label="区域名称"
            ></el-table-column>
            <el-table-column
              prop="energyTypeName"
              header-align="center"
              align="center"
              label="分类"
              width="70"
            ></el-table-column>
            <el-table-column
              prop="bqVal"
              header-align="center"
              align="center"
              label="本期用能"
            ></el-table-column>
            <el-table-column
              prop="tqVal"
              header-align="center"
              align="center"
              label="同期用能"
            ></el-table-column>
            <el-table-column
              prop="hqVal"
              header-align="center"
              align="center"
              label="环期用能"
            ></el-table-column>
            <el-table-column
              prop="tbPercent"
              header-align="center"
              align="center"
              label="同比比率"
            ></el-table-column>
            <el-table-column
              prop="hbPercent"
              header-align="center"
              align="center"
              label="环比比率"
            ></el-table-column>
             <el-table-column
              prop="date"
              header-align="center"
              align="center"
              label="时间"
            ></el-table-column>
          </el-table>
        </div>
      </el-main>
    </el-container>
  </div>
  </d2-container>
</template>

<script>
import * as Util from "@/utils";
import * as Echarts from 'echarts'
import Config from "@/utils/config"
import Minix from './mixin'
export default {
  name: "areaPage",
  mixins:[Minix],
  data() {
    return {
      sored:true,
      Config:Config,
      dataForm: {
        date:new Date(),
        dateType:'',
        energyType:''
      },
      page: {
        page: 1,
        total: 0,
        size: 10
      },
      menuListTreeProps: {
        label: "buildingName",
        children: "children"
      },
      unit:'',
      dataList: [],
      meterTypeList:[],
      currentbuildInfo: {},
      departTableDataList:[],
      sourceData:[],//未经处理的源数据
      businessChart:{
          chart:"",
          x:['1F','2F','3F','4F','5F','6F','7F','8F','9F','10F','11F','12F','14F','13F','15F','16F','17F','18F','19F','20F','21F','22F','23F'],
          y:[0,10240,102400,1048576,10485760],
          data:[9,7,8,5,4,6,8,9,7,8,5,4,6,8,9,7,8,5,4,6,8,3,4],
          legendData:[{name:'电'}],
          warn:9,
          title:"用能情况"
      },
      businessChartTwo:{
          data:[{name:'区域1',value:21},{name:'区域2',value:13},{name:'区域3',value:21},{name:'区域4',value:16},{name:'区域5',value:21},],
          legendData:['区域1','区域2','区域3','区域4','区域5'],
          title:"区域用能比例"
      },
      businessChartThree:{
        title:'能耗对比',
        legendData:{right:140,data: ['同期', '本期', '同比']},
        xAxisData:['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        yAxisName:['单位 kw/h','比率'],
        seriesData:{
          data1: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
          data2:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
          data3: [2.0, -2.2, 3.3, -4.5, 6.3, -10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]
        },
        color:['#2BD597','#708DE5','#F6AD35'],
      },
      showchart:true,
    };
  },
  computed: {
    containerHeight() {
      return Util.getClientHeight() - 143;
    },
    chartHeight(){
       return Util.getClientHeight() - 300;
    }
  },
  created() {
    this.dataForm.dateType=Config.searchDate[0].date;
    this.queryStatic("METER_TYPE");
  },
  methods: {
    exoprtData(){
      // 导出数据
      let header=['序号','区域','分类','本期用能','同期用能','环期用能','同比比率','环比比率','时间']
      let props=['index','buildName','energyTypeName','bqVal','tqVal','hqVal','tbPercent','hbPercent','date']
      let fileName=`区域用${ this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue}统计`
      this.export2Excel(header,props,fileName,this.departTableDataList)
    },
    export2Excel (tH, fi, fiNa, dataList) {
      var tHeader = tH
      var filterVal = fi
      var fileName = fiNa
      require.ensure([], () => {
        const {export_json_to_excel} = require('@/utils/Export2Excel.js')
        const list = dataList
        const data = this.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, fileName)
      })
    },
    formatJson (filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    /**
     * 获取参数枚举
     */
    queryStatic(type) {
      this.$api.okhttp({
        url: this.$http.adornUrl('/sys/sysstaticdata/getList'),
        method: 'get',
        params: this.$http.adornParams({
          'code': type ,
          "customerId":this.$util.cookies.get('customer_id')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.meterTypeList = data.page
          this.dataForm.energyType = data.page[0].paramKey;
          this.unit = data.page[0].paramExt;

        } else {
          this.meterTypeList = []
        }
        this.getDataList();
    });
    },
    // 获取区域数据列表
    getDataList (type) {
      if(type){
        this.pageIndex = 1
      }
      this.$api.okhttp({
        url: this.$http.adornUrl("/ecs/ecsbuildinginfo/select"),
        method: "get",
        params: this.$http.adornParams({
          page: this.page.pageIndex,
          limit: this.page.pageSize,
          key: this.dataForm.key,
          customerId: this.$util.cookies.get("customer_id"),
          projectid:this.$util.cookies.get("cuuren_projectId")
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.currentbuildInfo = (data.menuList&&data.menuList.length>0)?data.menuList.find(item=>item.parentBuildingId==-1):{},
          this.dataList = Util.treeDataTranslate(
            data.menuList,
            "buildingId",
            "parentBuildingId"
          );
          this.$nextTick(() => {
            this.$refs.buildTree.setCurrentKey(this.currentbuildInfo.buildingId);
          });
        } else {
          this.dataList = [];
        }
        this.getPowerDataList();
      });
    },
    changeShowType(){
      this.showchart = !this.showchart;
    },
    initBarChartOne(opt,obj){
        let self=this
        let option={
            grid:{
              x:50,
              y:30,
              x2:55,
              y2:25,
            },
            title:{
                text:opt.title,
                show:true,
                left:'center',
                top:5,
                textStyle:{
                    color:"#ccc",
                    fontSize:14,
                    fontFamily:"MicrosoftYaHei",
                    lineHeight:14,
                },
                padding:0,
            },
            tooltip: {
              trigger: 'item',
              formatter: '{b}:{c}'+ this.unit,
            },
            toolbox: {
              show: true,
              top:-6,
              right:40,
              feature: {
                myTool1: {    //必须要my开头
                  show: true,
                  title: '排名',
                  iconStyle: {
                    borderColor: 'green'
                  },
                  icon:'image://',
                  onclick: function (){
                   self.drawChartOneSort()
                  }
                }
              }
            },
            legend:{
              right:80,
              top:-5,
              data:opt.legendData,
            },
            xAxis:{
                type:'category',
                data:opt.x,
                axisLine:{
                    lineStyle:{
                        color:"#2C73D2",
                        type:'solid',
                        width:0.5
                    },
                },
                axisLabel:{
                    color:"#ccc",
                    interval:0,
                },
                axisTick: {
                  show:false,
                  alignWithLabel: true
                }
            },
            yAxis:{
                type:'value',
                name:'单位 '+self.unit,
                data:opt.y,
                axisLabel:{
                    color:"#ccc",
                },
                axisLine:{
                    lineStyle:{
                        color:"#ccc",
                        type:'soild',
                        opacity:0,
                    }
                },
                axisLabel:{
                    formatter:function(value,index){
                      return value;
                    }
                },
                axisTick: {
                    show:false,
                    alignWithLabel: true
                },
                splitLine:{
                    lineStyle:{
                        color:"#2C73D2",
                        type:"dotted",
                        opacity:0.5,
                    }
                },
            },
            series: [{
                name: opt.legendData[0].name,
                type: 'bar',
                data: opt.data[0],
                barCategoryGap:'40%',
                itemStyle:{
                  normal: {
                    barBorderRadius:[14,14,0,0],
                  },
                }
            }],
          color:['#4C7EDF','#FFCC00', '#00CC33', '#D05454',]
        }
        opt.chart = Echarts.init(document.getElementById(obj));
        opt.chart.setOption(option);
    },
    initBarChartTwo(opt,obj){
        let option={
           grid:{
              x:10,
              y:15,
              x2:15,
              y2:15,
            },
            title:{
                text:opt.title,
                show:true,
                left:'center',
                top:5,
                textStyle:{
                    color:"#ccc",
                    fontSize:14,
                    fontFamily:"MicrosoftYaHei",
                    lineHeight:14,
                },
                padding:0,
            },
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
              type: 'scroll',
              orient: 'vertical',
              right: 0,
              top: '24%',
              bottom: 20,
              data: opt.legendData
            },
            series: [{
              name: '区域用能比例',
              type: 'pie',
              radius: '80%',
              center: ['34%', '55%'],
              data: opt.data,
              label: {
                  show: false,
                  position: 'center',
                  normal: {
                    position: 'inner',
                    show : false
                  }
              },
              emphasis: {
                  itemStyle: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
              },
              labelLine: {
                  show: false
              },
          }],
          color:['#708DE5','#2BD597', '#F6AD35','#708ce5', '#446cea', '#0bc783','#2bd597']
        }
        opt.chart = Echarts.init(document.getElementById(obj));
        opt.chart.setOption(option);
    },
    initBarChartThree(opt,obj){
      let self=this
      let option={
          grid:{
              x:50,
              y:25,
              x2:55,
              y2:25,
              top:60,
          },
          title:{
              text:opt.title,
              show:true,
              left:'center',
              textStyle:{
                  color:"#ccc",
                  fontSize:14,
                  fontFamily:"MicrosoftYaHei",
                  lineHeight:14,
              },
              padding:5,
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                  color: '#999'
              }
            }
          },
          toolbox: {
            show: true,
            right:30,
            feature: {
              myTool1: {    //必须要my开头
                show: true,
                title: '同比',
                iconStyle: {
                  borderColor: 'green'
                },
                icon:'image://',
                onclick: function (){
                  self.tongbiShow()
                }
              },
              myTool2: {    //必须要my开头
                show: true,
                title: '环比',
                iconStyle: {
                  borderColor: 'green'
                },
                icon:'image://',
                onclick: function (){
                  self.huanbiShow()
                }
              }
            }
          },
          legend: opt.legendData,
          xAxis: [
              {
                type: 'category',
                data: opt.xAxisData,
                axisPointer: {
                  type: 'shadow'
                }
              }
          ],
          yAxis: [
              {
                  type: 'value',
                  name: opt.yAxisName[0],
                  // min: 0,
                  // max: 250,
                  // interval: 50,
                  axisLabel: {
                      formatter: '{value}'
                  }
              },
              {
                  type: 'value',
                  name: opt.yAxisName[1],
                  // min: 0,
                  // max: 25,
                  // interval: 5,
                  axisLabel: {
                    formatter: '{value}'
                  }
              }
          ],
          series: [
             {
                name: opt.legendData.data[0],
                type: 'bar',
                data: opt.seriesData.data1,
                itemStyle:{
                  normal: {
                    barBorderRadius:[14,14,0,0],
                  },
                },
              },
              {
                name:  opt.legendData.data[1],
                type: 'bar',
                data: opt.seriesData.data2,
                itemStyle:{
                  normal: {
                    barBorderRadius:[14,14,0,0],
                  },
                },
              },
              {
                name:  opt.legendData.data[2],
                type: 'line',
                yAxisIndex: 1,
                data:opt.seriesData.data3
              }
          ],
          color:opt.color
      }
      opt.chart = Echarts.init(document.getElementById(obj));
      opt.chart.setOption(option);
    },
    tongbiShow(){
      //展示同比数据
      this.businessChartThree.color=['#2BD597','#708DE5', '#F6AD35']
      this.businessChartThree.legendData.data=['同期','本期','同比'];
      this.businessChartThree.seriesData.data1=this.chartThreeData.tqDataList;
      this.businessChartThree.seriesData.data3=this.chartThreeData.tqDataPercentList;
      this.initBarChartThree(this.businessChartThree,'businessChartCompare');
    },
    huanbiShow(){
      this.businessChartThree.color=['#35e2cc','#708DE5', '#a76a0b']
      this.businessChartThree.legendData.data=['环期','本期','环比'];
      this.businessChartThree.seriesData.data1=this.chartThreeData.hqDataList;
      this.businessChartThree.seriesData.data3=this.chartThreeData.hqDataPercentList;
      this.initBarChartThree(this.businessChartThree,'businessChartCompare');
    },
    drawChartOneSort(){
      //排序渲染
      let result = JSON.parse(JSON.stringify(this.sourceData.child))
      if(this.sored){
        result=result.sort((a,b)=>a.val-b.val);
        this.sored = false
      }else{
        this.sored = true
      }

      this.businessChart.x=[]
      this.businessChart.data[0]=[]
      result.forEach(item=>{
        this.businessChart.x.push(item.buildName)
        this.businessChart.data[0].push(item.val)
      })
      this.initBarChartOne(this.businessChart,'businessAreaChart');
    },
    getPowerDataList() {
      let date= this.dataForm.date?this.formarDate(this.dataForm.dateType,new Date(this.dataForm.date)):''
      let params = {
          // buildingId: "-1",
          // customerId: "115",
          // date: "202004",
          // dateType: "2",
          // meterType: "1",
          customerId: this.$util.cookies.get("customer_id"),
          dateType:Config.searchDate.find(item=>item.date==this.dataForm.dateType).typeDesc,//1日2月3年
          date:date,
        //  buildingId:this.currentbuildInfo.buildingId,
          pbuildingId:this.currentbuildInfo.buildingId,
          meterType:this.dataForm.energyType,//分类type
      }
      this.$api.okhttp({
        url: this.$http.adornUrl('/ecm/area/list'),
        method: 'post',
        data: this.$http.adornData(params)
      }).then((data) => {
        if (data && data.code === 0) {
       //   console.log('所有数据',data.data)
          this.handleDataList(data.data.values,data.data.child)
          this.sourceData=data.data
        }
      });
    },
    handleDataList(data,child){
      //处理返回的所有的数据
      this.businessChart={
          chart:"",
          x:[],
          data:[[]],
          title:""
      },
      this.businessChartTwo={
          data:[],
          legendData:[],
          title:""
      },
      this.businessChartThree={
        title:'',
        legendData:{
          right:140,
          data: []
        },
        xAxisData:[],
        yAxisName:[],
        seriesData:{
          data1: [],
          data2:[],
          data3: []
        },
        color:['#2BD597','#708DE5','#F6AD35']
      }
      this.chartThreeData={
        isTqData:true,//表示当前是同期还是环期
        bqDataList:[],//本期数值
        tqDataPercentList:[],//同期比率
        hqDataPercentList:[],//环期比率
        tqDataList:[],//同期数据
        hqDataList:[]//环期数据
      }
      this.departTableDataList=[]
      let selectType=this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue
      this.businessChart.title=`用${selectType}统计`;
      this.businessChart.legendData=[{name:selectType}],
      this.businessChartTwo.title=`区域用${selectType}比例`;
      this.businessChartThree.title=`${selectType}-能耗对比`;
      this.businessChartThree.yAxisName=[`单位${this.unit}`,'比率'];
      data.forEach((item,index)=>{
        //图表一
        // this.businessChart.x.push(item.dateDetail)
        // this.businessChart.data[0].push(item.val)
        //图表三
        let tqP=item.tqVal?(((item.val-item.tqVal)/item.tqVal)*100):0
        let hqP=item.hqVal?(((item.val-item.hqVal)/item.hqVal)*100):0
        this.chartThreeData.tqDataPercentList.push(tqP.toFixed(2))//计算同期比率
        this.chartThreeData.hqDataPercentList.push(hqP.toFixed(2))//计算环期比率
        this.chartThreeData.bqDataList.push(item.val)
        this.chartThreeData.tqDataList.push(item.tqVal)
        this.chartThreeData.hqDataList.push(item.hqVal)
        this.businessChartThree.xAxisData.push(item.dateDetail)
        //表格数据
        this.departTableDataList.push({
             index:index+1,
             dateDetail:item.dateDetail,
             buildName:this.currentbuildInfo.buildingName,
             energyTypeName:this.meterTypeList.find(item=>item.paramKey==this.dataForm.energyType).paramValue,
             bqVal:item.val+this.unit,
             tqVal:item.tqVal+this.unit,
             hqVal:item.hqVal+this.unit,
             tbPercent:tqP.toFixed(2)+'%',
             hbPercent:hqP.toFixed(2)+'%',
             date:(this.dataForm.date&&this.dataForm.date!="")?this.dataForm.dateType=='date'?Util.dateFormat(Config.searchDate.find(ele=>ele.date==this.dataForm.dateType).formatStr,this.dataForm.date)+' '+item.dateDetail+'H':Util.dateFormat(Config.searchDate.find(ele=>ele.date==this.dataForm.dateType).formatStr,this.dataForm.date)+'-'+item.dateDetail:'',
           }
        )
      })
      child.forEach((item,index)=>{
        //图表二
        this.businessChartTwo.data.push({name:item.buildName,value:item.val});
        this.businessChartTwo.legendData.push(item.buildName);
        //图表一
        this.businessChart.x.push(item.buildName)
        this.businessChart.data[0].push(item.val)
      })
      this.initBarChartOne(this.businessChart,'businessAreaChart');
      this.initBarChartTwo(this.businessChartTwo,'chartTwo');
      this.businessChartThree.legendData.data=['同期', '本期', '同比'];
      this.businessChartThree.seriesData.data1=this.chartThreeData.tqDataList;
      this.businessChartThree.seriesData.data2=this.chartThreeData.bqDataList;
      this.businessChartThree.seriesData.data3=this.chartThreeData.tqDataPercentList;
      this.initBarChartThree(this.businessChartThree,'businessChartCompare');
    },
    selectBuild(data){
      this.currentbuildInfo = data;
      this.getPowerDataList();
    }
  },
  watch:{
    'dataForm.energyType':function(newV,oldV){
      this.unit = this.meterTypeList.find(item => item.paramKey == newV).paramExt;
    },
    'dataForm.dateType':function(newV,oldV){
        let str=''
        switch(newV){
          case 'date':
            str= Util.dateFormat('YYYY-mm-dd',new Date())
            break;
          case 'month':
            str=Util.dateFormat('YYYY-mm',new Date())
            break;
          case 'year':
            str=Util.dateFormat('YYYY',new Date())
            break;
        }
        this.dataForm.date=str;
    }
  }
};
</script>

<style scoped>
.tree-area { background-color: rgba(0, 0, 0, 0.1);
  width: 200px !important;
  /* box-shadow: 0px 0px 2px 2px #f7f6f6; */
  padding-top: 10px;
}
.bg-white {
  box-shadow: 0px 0px 2px 2px #f7f6f6;
}
.el-tree-node__content {
  height: 30px !important;
}
.busi-chart{
    width: 100%;
    height: 250px;
    margin-top: 10x;
    margin-bottom: 20px;
}
.el-form-item{
  margin-bottom: 0px;
}
.search-area{
   display:flow-root;
   margin-bottom: 15px;
   border: 1px solid #e8e8e8;
   border-left: none;
   border-right: none;
   padding: 10px 0px;
}
</style>
